package com.ita.aspect;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import com.ita.pojo.Customer;

@Component
@Aspect
public class CheckAspect {

	private MessageDigest digest;
	private final String P1 = "execution(* com.ita.service.CustomerService.regist(..))";
	private final String P2 = "execution(* com.ita.service.CustomerService.login(..))";

	public CheckAspect() {
		try {
			digest = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

	@Around(value = P1)
	public Object regist(ProceedingJoinPoint point) {

		Object o = null;
		try {
			Customer u = (Customer) point.getArgs()[0];
			u.setPassword(process(u.getPassword()));
			o = point.proceed(new Object[] { u });
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return o;
	}

	@Around(value = P2)
	public Object login(ProceedingJoinPoint point) {

		Object o = null;
		try {
			String pwd = (String) point.getArgs()[1];
			String pwd1 = process(pwd);
			o = point.proceed(new Object[] { point.getArgs()[0], pwd1 });
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return o;
	}

	private String process(String s) {
		String ss = "";
		try {
			byte[] bs = digest.digest(s.getBytes("ISO-8859-1"));
			ss = new String(bs, "ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return ss;
	}

}
